﻿
#region Usings
using System.Collections.Generic;

using PolyGameEngine.GamePieces.Common;
using PolyGameEngine.Tools;

using FarseerPhysics.Common;
using FarseerPhysics.Common.Decomposition;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

#endregion

namespace PolyGameEngine.GamePieces
{
    public class TextureGamePiece : GamePiece
    {
        //  Vertices verts
        Vertices verts;
        public BreakableBody b;
        public TextureGamePiece(PhysicsGame PhysicsGame, World World, Material Material, Texture2D ShapeTexture, Vector2 Position, float Rotation, float DrawingDepth, int saveLineIndex, string GPID)
            : base(PhysicsGame, World, Material, Position, Rotation, DrawingDepth, saveLineIndex, GPID)
        {
            
            sprite = new Sprite(ShapeTexture);
            uint[] data = new uint[ShapeTexture.Width * ShapeTexture.Height];
            ShapeTexture.GetData<uint>(data);
            verts = PolygonTools.CreatePolygon(data, ShapeTexture.Width, false);
            Vector2 Scale = new Vector2(0.01f, 0.01f);
            friction = 10;
            restitution = -.2f;
            Vector2 centroid = -verts.GetCentroid();
            verts.Translate(ref centroid);
            sprite.Origin = -centroid;
            List<Vertices> list = BayazitDecomposer.ConvexPartition(verts);


            //scale the vertices from graphics space to sim space
            Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1));

            foreach (Vertices vertices in list)
            {
                vertices.Scale(ref vertScale);

            }

            FixtureFactory.AttachCompoundPolygon(list, 1, body);
            foreach (Fixture fix in body.FixtureList)
            {
                fix.OnCollision = null;
                fix.OnSeparation = null;
            }
            body.OnCollision += HandleDefaultCollision;
            body.OnSeparation += HandleDefaultAfterCollision;
        }

        //override om die base constructor te skip oor ons ons eie texture hier wil gebruik.
        public override void Initialize()
        {
            userData = this;
            rotation = r;

        }




    }
}
